﻿using NPlurk;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Windows.Forms;
using WindowsLive.Writer.Api;
using Microsoft.Win32;

namespace WLWPlurk
{
    [WriterPlugin("57D8839B-D197-4952-8AC1-BF48A06C361D", "WLW Plurk",
        PublisherUrl = "http://wlwextensionlearning.blogspot.com/",
        Description = "Help you to send a plurk after you publish new post",
        ImagePath = "plurk.png",
        HasEditableOptions = false)]

    public class WLWPlurk : PublishNotificationHook
    {
        public override bool OnPrePublish(IWin32Window dialogOwner,
            IProperties properties, IPublishingContext publishingContext,
            bool publish)
        {
            return true;
        }

        public override void OnPostPublish(IWin32Window dialogOwner,
            IProperties properties, IPublishingContext publishingContext,
            bool publish)
        {
            // If this post is a draft (false), don't do anything
            // if it's an actual publish, then publish = true;
            if (!publish)
                return;

            //publishingContext.PostInfo.ToString().Split
            string TinyPermalink = ToTinyURL(publishingContext.PostInfo.Permalink);
            //remove http:// becuase "//" will be remove on NPlurk.
            TinyPermalink = TinyPermalink.Remove(0, 7);

            string updatePlurk = string.Format("{1} ({0})",
                publishingContext.PostInfo.Title,
                TinyPermalink);

            // Code to update Twitter
            string plurkKey = ""; // fill your plurk key from http://www.plurk.com/API/
            string username = ""; // fill your plurk account
            string password = ""; // fill your plurk password

            var plurk = new PlurkStub(plurkKey);

            Profile profile = plurk.Login(username, password);

            var newPlurk = plurk.AddPlurk(updatePlurk);
            Completions completions = plurk.GetCompletion();
        }

        public string ToTinyURL(string OriURL)
        {
            string ConvertUrl = "http://tinyurl.com/api-create.php?url=" + OriURL;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ConvertUrl);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader tReader = new StreamReader(response.GetResponseStream());
            return tReader.ReadToEnd();
        }
    }
}
